package com.spedencencies.springjdbc2.service;

import com.spedencencies.springjdbc2.model.Event;
import com.spedencencies.springjdbc2.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author zhizhou   2024/10/9 14:15
 */
@Service
public class EventService {
    private final JdbcTemplate jdbcTemplate;
    
    @Autowired
    public EventService(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }
    
    // 保存事件时间到数据库
    public void saveEvent(String dateTimeStr) {
        LocalDateTime eventTime = DateUtils.parseDateTime(dateTimeStr);
        String sql = "INSERT INTO events (event_time) VALUES (?)";
        jdbcTemplate.update(sql, java.sql.Timestamp.valueOf(eventTime));
    }
    
    // 根据 ID 查询事件
    public Event getEventById(Long id) {
        String sql = "SELECT * FROM events WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, new EventRowMapper(), new Object[]{id});
    }
    
    // 更新事件时间
    public void updateEvent(Long id, String newDateTimeStr) {
        LocalDateTime newEventTime = DateUtils.parseDateTime(newDateTimeStr);
        String sql = "UPDATE events SET event_time = ? WHERE id = ?";
        jdbcTemplate.update(sql, java.sql.Timestamp.valueOf(newEventTime), id);
    }
    
    // 根据 ID 删除事件
    public void deleteEvent(Long id) {
        String sql = "DELETE FROM events WHERE id = ?";
        jdbcTemplate.update(sql, id);
    }
    
    // 查询所有事件
    public List<Event> getAllEvents() {
        String sql = "SELECT * FROM events";
        return jdbcTemplate.query(sql, new EventRowMapper());
    }
    
    // RowMapper 实现
    private static class EventRowMapper implements RowMapper<Event> {
        @Override
        public Event mapRow(ResultSet rs, int rowNum) throws SQLException {
            Long id = rs.getLong("id");
            LocalDateTime eventTime = rs.getTimestamp("event_time").toLocalDateTime();
            String eventTimeStr = DateUtils.formatDateTime(eventTime);
            return new Event(id, eventTime, eventTimeStr);
        }
    }
}
